package com.yequan.thread.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yq
 * @date 2020/09/04
 */
public class SemaphoreDemo1 {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(10);
        int threadCount = 30;
        AtomicInteger num = new AtomicInteger(0);
        ExecutorService threadPool = Executors.newFixedThreadPool(30);
        for (int i = 0; i < threadCount; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println(num.addAndGet(1));
                        Thread.sleep(5000);
                        System.out.println("正在等待许可证的线程：" + semaphore.getQueueLength());
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }

}
